/**交互 */

export const operateMgr = {
    primaryServiceUUID: 'f0080001-0451-4000-b000-000000000000',
    test_CT_r_UUID: 'f0080002-0451-4000-b000-000000000000', // 读
    test_CT_w_UUID: 'f0080003-0451-4000-b000-000000000000', // 写
    callbackDic: {},
    isLink: false,
    setCallback(_protocol, onback1) {
        if (onback1 != null) {
            this.callbackDic[_protocol] = onback1;
        }
    },

    protocolHex(_protocol) {
        return "0x" + _protocol;
    },

    async link(_gatt_server) {
        if (this.isLink == false) {
            const test_Service = await _gatt_server.getPrimaryService(this.primaryServiceUUID);

            this.characteristic_w = await test_Service.getCharacteristic(this.test_CT_w_UUID);
            this.characteristic_r = await test_Service.getCharacteristic(this.test_CT_r_UUID);

            this.characteristic_r.oncharacteristicvaluechanged = this.OnRev;
            //this.characteristic_r.addEventListener('characteristicvaluechanged', onFun);
            this.characteristic_r.startNotifications();
        }
    },

    writeValue(uint8Array)
    {
        operateMgr.characteristic_w.writeValue(uint8Array);
    },

    OnRev(evt){
        //console.log('OnRev data changed:',evt,evt.target.value);
        var dataView = evt.target.value;
        // console.log("dataView.byteLength",dataView.byteLength,dataView);
        const hexArray = operateMgr.dataViewToHexArray(dataView, dataView.byteLength);
        const cmd = hexArray[0].toString();
        console.log('OnRev data changed:', cmd);
        if (cmd in operateMgr.callbackDic) {
            console.log('OnRev data changed:', evt, evt.target.value);
            operateMgr.callbackDic[cmd](cmd, dataView,hexArray);
        }
    },

    To16(decimalNumber) {
        let hexNumberWithPrefix = "0x" + decimalNumber.toString(16);
        return hexNumberWithPrefix;
    },

    dataViewToHexArray(dataView, byteLength) {
        const hexArray = [];
        for (let i = 0; i < byteLength; i++) {
            const byte = dataView.getUint8(i); // 读取一个无符号8位整数（即一个字节）  
            const hexString = byte.toString(16).padStart(2, '0').toUpperCase(); // 转换为十六进制字符串，并确保有两个字符  
            hexArray.push(hexString);
        }
        return hexArray;
    }
}